package cn.ssm_05.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 日志增强Aop处理类
 */
@Component //定义组件bean
@Aspect//定义切面
public class LogAop {

	//使用slf4j
	private Logger logger = LoggerFactory.getLogger(LogAop.class);

	//切入点
	@Pointcut("execution(* cn.ssm_05.service..*.*(..))")
	public void logPointcut(){
		
	}
	/**
	 * 环绕增强
	 * @param joinPoint
	 */
	@Around("logPointcut()")
	public void around(ProceedingJoinPoint joinPoint){
		try {
			logger.info("环绕增强方法之前:{}",
					joinPoint.getSignature()
					);
			
			//代理对象调用方法的返回值
			Object object = joinPoint.proceed();

			logger.info("环绕增强方法之后:{} 返回值{}",
					joinPoint.getSignature(),
					object
					);
		} catch (Throwable e) {
			e.printStackTrace();
			
			logger.info("异常增强方法:{},异常{}",
					joinPoint.getSignature(),
					e.getMessage()
					);
		}
	}
	
	/**
	 * 前置增强方法
	 * 
	 * @param joinPoint
	 *            连接点 获取目标对象 获取方法 获取参数
	 */
	@Before("logPointcut()")
	public void before(JoinPoint joinPoint) {
		logger.info("前置增强方法:{},参数{}",
				joinPoint.getSignature(),
				Arrays.toString(joinPoint.getArgs())
				);
	}

	/**
	 * 后置增强方法
	 * @param joinPoint
	 * @param result 目标对象执行方法的返回值
	 */
	@AfterReturning(value = "logPointcut()",returning = "obj")
	public void afterReturning(JoinPoint joinPoint,Object obj) {
		logger.info("后置增强方法:{},返回值{}",
				joinPoint.getSignature(),
				obj
				);
	}
	
	/**
	 * 异常增强处理
	 * @param joinPoint
	 * @param e 出现的异常对象
	 */
	@AfterThrowing(value ="logPointcut()",throwing = "e")
	public void afterThrowing(JoinPoint joinPoint,RuntimeException e){
		logger.info("异常增强方法:{},异常{}",
				joinPoint.getSignature(),
				e.getMessage()
				);
	}
	
	/**
	 * 最终增强
	 * @param joinPoint
	 */
	@After("logPointcut()")
	public void after(JoinPoint joinPoint){
		logger.info("最终增强方法:{}",
				joinPoint.getSignature()
				);
	}
	
	
}
